[[...path]].page.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, isClient, isIPageInfoForEntity, isServer, IUser, IUserHasId, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import ExtensibleCustomError from 'extensible-custom-error';
  7. import { model as mongooseModel } from 'mongoose';
  8. import {
  9. NextPage, GetServerSideProps, GetServerSidePropsContext,
  10. } from 'next';
  11. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  12. import dynamic from 'next/dynamic';
  13. import Head from 'next/head';
  14. import { useRouter } from 'next/router';
  15. import superjson from 'superjson';
  16. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  17. import { PageComment } from '~/components/PageComment';
  18. // import { useTranslation } from '~/i18n';
  19. // import CommentEditorLazyRenderer from '~/components/PageComment/CommentEditorLazyRenderer';
  20. import { CrowiRequest } from '~/interfaces/crowi-request';
  21. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  22. // import { useIndentSize } from '~/stores/editor';
  23. // import { useRendererSettings } from '~/stores/renderer';
  24. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  25. import { CustomWindow } from '~/interfaces/global';
  26. import { RendererConfig } from '~/interfaces/services/renderer';
  27. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  28. import { IUserUISettings } from '~/interfaces/user-ui-settings';
  29. import { PageModel, PageDocument } from '~/server/models/page';
  30. import { PageRedirectModel } from '~/server/models/page-redirect';
  31. import { UserUISettingsModel } from '~/server/models/user-ui-settings';
  32. import { useSWRxCurrentPage, useSWRxIsGrantNormalized, useSWRxPageInfo } from '~/stores/page';
  33. import { useRedirectFrom } from '~/stores/page-redirect';
  34. import {
  35. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth, useSelectedGrant,
  36. } from '~/stores/ui';
  37. import loggerFactory from '~/utils/logger';
  38. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  39. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  40. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  41. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  42. import { BasicLayout } from '../components/Layout/BasicLayout';
  43. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  44. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  45. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  46. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  47. import {
  48. useCurrentUser, useCurrentPagePath,
  49. useIsLatestRevision,
  50. useIsForbidden, useIsNotFound, useIsTrashPage, useIsSharedUser,
  51. useIsEnabledStaleNotification, useIsIdenticalPath,
  52. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  53. useHackmdUri,
  54. useIsAclEnabled, useIsUserPage, useIsNotCreatable,
  55. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  56. useIsSlackConfigured, useIsBlinkedHeaderAtBoot, useRendererConfig, useEditingMarkdown,
  57. } from '../stores/context';
  58. import {
  59. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  60. } from './utils/commons';
  61. // import { useCurrentPageSWR } from '../stores/page';
  62. const logger = loggerFactory('growi:pages:all');
  63. const {
  64. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage,
  65. } = pagePathUtils;
  66. const { removeHeadingSlash } = pathUtils;
  67. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  68. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  69. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  70. {
  71. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  72. return v?.data != null
  73. && v?.data.toObject != null
  74. && v?.meta != null
  75. && isIPageInfoForEntity(v.meta);
  76. },
  77. serialize: (v) => {
  78. return {
  79. data: superjson.stringify(v.data.toObject()),
  80. meta: superjson.stringify(v.meta),
  81. };
  82. },
  83. deserialize: (v) => {
  84. return {
  85. data: superjson.parse(v.data),
  86. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  87. };
  88. },
  89. },
  90. 'IPageToShowRevisionWithMetaTransformer',
  91. );
  92. const IdenticalPathPage = (): JSX.Element => {
  93. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  94. return <IdenticalPathPage />;
  95. };
  96. const PutbackPageModal = (): JSX.Element => {
  97. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  98. return <PutbackPageModal />;
  99. };
  100. type Props = CommonProps & {
  101. currentUser: IUser,
  102. pageWithMeta: IPageToShowRevisionWithMeta,
  103. // pageUser?: any,
  104. redirectFrom?: string;
  105. // shareLinkId?: string;
  106. isLatestRevision?: boolean
  107. isIdenticalPathPage?: boolean,
  108. isForbidden: boolean,
  109. isNotFound: boolean,
  110. IsNotCreatable: boolean,
  111. // isAbleToDeleteCompletely: boolean,
  112. isSearchServiceConfigured: boolean,
  113. isSearchServiceReachable: boolean,
  114. isSearchScopeChildrenAsDefault: boolean,
  115. isSlackConfigured: boolean,
  116. // isMailerSetup: boolean,
  117. isAclEnabled: boolean,
  118. // hasSlackConfig: boolean,
  119. // drawioUri: string,
  120. hackmdUri: string,
  121. // mathJax: string,
  122. // noCdn: string,
  123. // highlightJsStyle: string,
  124. // isAllReplyShown: boolean,
  125. // editorConfig: any,
  126. isEnabledStaleNotification: boolean,
  127. // isEnabledLinebreaks: boolean,
  128. // isEnabledLinebreaksInComments: boolean,
  129. // adminPreferredIndentSize: number,
  130. // isIndentSizeForced: boolean,
  131. disableLinkSharing: boolean,
  132. rendererConfig: RendererConfig,
  133. // UI
  134. userUISettings?: IUserUISettings
  135. // Sidebar
  136. sidebarConfig: ISidebarConfig,
  137. };
  138. const GrowiPage: NextPage<Props> = (props: Props) => {
  139. // const { t } = useTranslation();
  140. const router = useRouter();
  141. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  142. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  143. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  144. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  145. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  146. // register global EventEmitter
  147. if (isClient()) {
  148. (window as CustomWindow).globalEmitter = new EventEmitter();
  149. }
  150. // commons
  151. // useEditorConfig(props.editorConfig);
  152. useCsrfToken(props.csrfToken);
  153. // UserUISettings
  154. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  155. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  156. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  157. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  158. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  159. // page
  160. useIsLatestRevision(props.isLatestRevision);
  161. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  162. useIsForbidden(props.isForbidden);
  163. useIsNotFound(props.isNotFound);
  164. useIsNotCreatable(props.IsNotCreatable);
  165. useRedirectFrom(props.redirectFrom);
  166. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  167. // useShared();
  168. // useShareLinkId(props.shareLinkId);
  169. useIsSharedUser(false); // this page cann't be routed for '/share'
  170. useIsIdenticalPath(false); // TODO: need to initialize from props
  171. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  172. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  173. useIsBlinkedHeaderAtBoot(false);
  174. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  175. useIsSearchServiceReachable(props.isSearchServiceReachable);
  176. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  177. useIsSlackConfigured(props.isSlackConfigured);
  178. // useIsMailerSetup(props.isMailerSetup);
  179. useIsAclEnabled(props.isAclEnabled);
  180. // useHasSlackConfig(props.hasSlackConfig);
  181. // useDrawioUri(props.drawioUri);
  182. useHackmdUri(props.hackmdUri);
  183. // useMathJax(props.mathJax);
  184. // useNoCdn(props.noCdn);
  185. // useIndentSize(props.adminPreferredIndentSize);
  186. useDisableLinkSharing(props.disableLinkSharing);
  187. useRendererConfig(props.rendererConfig);
  188. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  189. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  190. // const { data: editorMode } = useEditorMode();
  191. const { pageWithMeta, userUISettings } = props;
  192. let shouldRenderPutbackPageModal = false;
  193. if (pageWithMeta != null) {
  194. shouldRenderPutbackPageModal = _isTrashPage(pageWithMeta.data.path);
  195. }
  196. const pageId = pageWithMeta?.data._id;
  197. useCurrentPageId(pageId);
  198. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  199. useSWRxPageInfo(pageId, undefined, pageWithMeta?.meta); // store initial data
  200. useIsTrashPage(_isTrashPage(pageWithMeta?.data.path ?? ''));
  201. useIsUserPage(isUserPage(pageWithMeta?.data.path ?? ''));
  202. useIsNotCreatable(props.isForbidden || !isCreatablePage(pageWithMeta?.data.path ?? '')); // TODO: need to include props.isIdentical
  203. useCurrentPagePath(pageWithMeta?.data.path);
  204. useCurrentPathname(props.currentPathname);
  205. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  206. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  207. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  208. // sync grant data
  209. useEffect(() => {
  210. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  211. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  212. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  213. useEffect(() => {
  214. const decodedURI = decodeURI(window.location.pathname);
  215. if (isClient() && decodedURI !== props.currentPathname) {
  216. router.replace(props.currentPathname, undefined, { shallow: true });
  217. }
  218. }, [props.currentPathname, router]);
  219. const classNames: string[] = [];
  220. // switch (editorMode) {
  221. // case EditorMode.Editor:
  222. // classNames.push('on-edit', 'builtin-editor');
  223. // break;
  224. // case EditorMode.HackMD:
  225. // classNames.push('on-edit', 'hackmd');
  226. // break;
  227. // }
  228. // if (page == null) {
  229. // classNames.push('not-found-page');
  230. // }
  231. return (
  232. <>
  233. <Head>
  234. {/*
  235. {renderScriptTagByName('drawio-viewer')}
  236. {renderScriptTagByName('mathjax')}
  237. {renderScriptTagByName('highlight-addons')}
  238. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  239. */}
  240. </Head>
  241. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  242. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={props.isContainerFluid}>
  243. <header className="py-0 position-relative">
  244. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  245. </header>
  246. <div className="d-edit-none">
  247. <GrowiSubNavigationSwitcher />
  248. </div>
  249. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  250. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  251. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  252. <div id="content-main" className="content-main grw-container-convertible">
  253. <div className="row">
  254. <div className="col">
  255. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  256. { !props.isIdenticalPathPage && (
  257. <>
  258. <PageAlerts />
  259. { props.isForbidden && <ForbiddenPage /> }
  260. { props.IsNotCreatable && <NotCreatablePage />}
  261. { !props.isForbidden && !props.IsNotCreatable && <DisplaySwitcher />}
  262. {/* <DisplaySwitcher /> */}
  263. <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
  264. {/* <PageStatusAlert /> */}
  265. </>
  266. ) }
  267. </div>
  268. </div>
  269. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  270. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  271. <div id="revision-toc-content" className="revision-toc-content"></div>
  272. </div>
  273. </div> */}
  274. </div>
  275. </div>
  276. <footer>
  277. <PageComment pageId={useCurrentPageId().data} isReadOnly={false} titleAlign="left" />
  278. {/* <CommentEditorLazyRenderer pageId={useCurrentPageId().data} /> */}
  279. </footer>
  280. <UnsavedAlertDialog />
  281. <DescendantsPageListModal />
  282. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  283. </BasicLayout>
  284. </>
  285. );
  286. };
  287. function getPageIdFromPathname(currentPathname: string): string | null {
  288. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  289. }
  290. class MultiplePagesHitsError extends ExtensibleCustomError {
  291. pagePath: string;
  292. constructor(pagePath: string) {
  293. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  294. this.pagePath = pagePath;
  295. }
  296. }
  297. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  298. const req: CrowiRequest = context.req as CrowiRequest;
  299. const { crowi } = req;
  300. const { revisionId } = req.query;
  301. const Page = crowi.model('Page') as PageModel;
  302. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  303. const { pageService } = crowi;
  304. let currentPathname = props.currentPathname;
  305. const pageId = getPageIdFromPathname(currentPathname);
  306. const isPermalink = _isPermalink(currentPathname);
  307. const { user } = req;
  308. if (!isPermalink) {
  309. // check redirects
  310. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  311. if (chains != null) {
  312. // overwrite currentPathname
  313. currentPathname = chains.end.toPath;
  314. props.currentPathname = currentPathname;
  315. // set redirectFrom
  316. props.redirectFrom = chains.start.fromPath;
  317. }
  318. // check whether the specified page path hits to multiple pages
  319. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  320. if (count > 1) {
  321. throw new MultiplePagesHitsError(currentPathname);
  322. }
  323. }
  324. const pageWithMeta: IPageToShowRevisionWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  325. const page = pageWithMeta?.data as unknown as PageDocument;
  326. // populate & check if the revision is latest
  327. if (page != null) {
  328. page.initLatestRevisionField(revisionId);
  329. await page.populateDataToShowRevision();
  330. props.isLatestRevision = page.isLatestRevision();
  331. }
  332. props.pageWithMeta = pageWithMeta;
  333. }
  334. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  335. const req = context.req as CrowiRequest<IUserHasId & any>;
  336. const { user } = req;
  337. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  338. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  339. if (userUISettings != null) {
  340. props.userUISettings = userUISettings.toObject();
  341. }
  342. }
  343. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  344. const req: CrowiRequest = context.req as CrowiRequest;
  345. const { crowi } = req;
  346. const Page = crowi.model('Page') as PageModel;
  347. const { currentPathname } = props;
  348. const pageId = getPageIdFromPathname(currentPathname);
  349. const isPermalink = _isPermalink(currentPathname);
  350. const page = props.pageWithMeta?.data;
  351. if (props.isIdenticalPathPage) {
  352. // TBD
  353. }
  354. else if (page == null) {
  355. props.isNotFound = true;
  356. props.IsNotCreatable = !isCreatablePage(currentPathname);
  357. // check the page is forbidden or just does not exist.
  358. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  359. props.isForbidden = count > 0;
  360. }
  361. else {
  362. props.isNotFound = page.isEmpty;
  363. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  364. if (isPermalink && page.isEmpty) {
  365. props.currentPathname = page.path;
  366. }
  367. // /path/to/page ==> /62a88db47fed8b2d94f30000
  368. if (!isPermalink && !page.isEmpty) {
  369. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  370. if (!isToppage) {
  371. props.currentPathname = `/${page._id}`;
  372. }
  373. }
  374. }
  375. }
  376. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  377. // const req: CrowiRequest = context.req as CrowiRequest;
  378. // const { crowi } = req;
  379. // const UserModel = crowi.model('User');
  380. // if (isUserPage(props.currentPagePath)) {
  381. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  382. // if (user != null) {
  383. // props.pageUser = JSON.stringify(user.toObject());
  384. // }
  385. // }
  386. // }
  387. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  388. const req: CrowiRequest = context.req as CrowiRequest;
  389. const { crowi } = req;
  390. const {
  391. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  392. } = crowi;
  393. props.isSearchServiceConfigured = searchService.isConfigured;
  394. props.isSearchServiceReachable = searchService.isReachable;
  395. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  396. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  397. // props.isMailerSetup = mailService.isMailerSetup;
  398. props.isAclEnabled = aclService.isAclEnabled();
  399. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  400. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  401. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  402. // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
  403. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  404. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  405. // props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  406. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  407. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  408. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  409. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  410. // props.editorConfig = {
  411. // upload: {
  412. // image: crowi.fileUploadService.getIsUploadable(),
  413. // file: crowi.fileUploadService.getFileUploadEnabled(),
  414. // },
  415. // };
  416. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  417. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  418. props.rendererConfig = {
  419. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  420. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  421. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  422. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  423. plantumlUri: process.env.PLANTUML_URI ?? null,
  424. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  425. // XSS Options
  426. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  427. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  428. tagWhiteList: crowi.xssService.getTagWhiteList(),
  429. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  430. };
  431. props.sidebarConfig = {
  432. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  433. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  434. };
  435. }
  436. /**
  437. * for Server Side Translations
  438. * @param context
  439. * @param props
  440. * @param namespacesRequired
  441. */
  442. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  443. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  444. props._nextI18Next = nextI18NextConfig._nextI18Next;
  445. }
  446. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  447. const req = context.req as CrowiRequest<IUserHasId & any>;
  448. const { user } = req;
  449. const result = await getServerSideCommonProps(context);
  450. // check for presence
  451. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  452. if (!('props' in result)) {
  453. throw new Error('invalid getSSP result');
  454. }
  455. const props: Props = result.props as Props;
  456. if (user != null) {
  457. props.currentUser = user.toObject();
  458. }
  459. try {
  460. await injectPageData(context, props);
  461. }
  462. catch (err) {
  463. if (err instanceof MultiplePagesHitsError) {
  464. props.isIdenticalPathPage = true;
  465. }
  466. else {
  467. throw err;
  468. }
  469. }
  470. await injectUserUISettings(context, props);
  471. await injectRoutingInformation(context, props);
  472. injectServerConfigurations(context, props);
  473. await injectNextI18NextConfigurations(context, props, ['translation']);
  474. return {
  475. props,
  476. };
  477. };
  478. export default GrowiPage;